#!/usr/bin/env python

import optparse
import sys

import histogram

from charmicat import BadCommandLineError

def main():
    '''
    bcat_merge_hists.py [opts] file.hpt file.hpt [file.hpt [...]]

    Accumulate histograms across multiple files into a single set of histograms.
    '''
    
    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-o", "--output", dest="output", default=None, 
                  help="Place output in FILE.hpt", metavar="FILE")

    opts, args = op.parse_args()

    if len(args) < 2:
        msg = "Please supply at least two histogram files to merge."
        raise BadCommandLineError(msg, -2)

    total_hd = {}
    count    = {}
    
    for path in args:
        try:
            hd = histogram.load(path)
        except AttributeError:
            print path
            continue

        for k in hd:
            if k in total_hd:
                total_hd[k] += hd[k]
                count[k] += 1
            else:
                total_hd[k] = hd[k]
                count[k] = 1

    if len(set(count.values())) != 1:
        sys.stderr.write("Not all histograms were present in every file")
        sys.stderr.write("--output file may contain incorrect results\n")

    histogram.dump(total_hd, opts.output)


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
